package com.penghaisoft.microwms.product.web.controller.intowarehouse;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.controller.BaseController;
import com.penghaisoft.microwms.common.dto.Resp;
import com.penghaisoft.microwms.common.dto.TransResult;
import com.penghaisoft.microwms.common.page.Pager;
import com.penghaisoft.microwms.common.service.IWmsCommonService;
import com.penghaisoft.microwms.common.wms.model.ProCheckIn;
import com.penghaisoft.microwms.product.service.IProCheckInService;

import lombok.extern.slf4j.Slf4j;

/** 
* @ClassName: ProCheckInController 
* @Description: 成品积压库存登记表
* @author luoteng
* @date 2018年11月5日 上午10:46:23  
*/
@RestController
@RequestMapping(value = "/intowarehouse/checkIn")
@Slf4j
public class ProCheckInController extends BaseController {
	
		@Autowired
		private IProCheckInService proCheckInService;
		
		@Autowired
		private IWmsCommonService wmsCommonService;
		
		@Resource
		private StringRedisTemplate stringRedisTemplate;//注入对象

	  /**
	   * 新增记录
	   * @param proCheckIn
	   * @return
	   */
		@PostMapping("c")
		public TransResult create(ProCheckIn proCheckIn) {
			proCheckIn.preInsert();
			Resp resp =  proCheckInService.create(proCheckIn);
			return fromResp(resp);
		}

	  /**
	   * 删除记录（逻辑删除active_flag=0)
	   * @param proCheckIn
	   * @return
	   */
		@PostMapping("del")
		public TransResult delete(ProCheckIn proCheckIn) {
			TransResult transResult = new TransResult();
			proCheckIn.setActiveFlag("1");
			
			List<ProCheckIn> list = proCheckInService.queryByAny(proCheckIn);
			if(list == null){
				transResult.setCode(Constant.FAIL);
				transResult.setMsg("请选择记录！");
				return transResult;
			}else{
				ProCheckIn tmp = list.get(0);
//				是否生成条码： 1：是 0：否
				if(tmp.getUserDefined2() != null && tmp.getUserDefined2().equals("1")){
					transResult.setCode(Constant.FAIL);
					transResult.setMsg("该成品积压库存登记单号已经生成条码，不能删除！");
					return transResult;
				}
				
//				if(tmp.getInAmount() != null && tmp.getInAmount() > 0) {
//					transResult.setCode(Constant.FAIL);
//					transResult.setMsg("该成品积压库存登记单号存在入库的条码，请先退扫再删除！");
//					return transResult;
//				}
				
				proCheckIn.setActiveFlag("0");
				proCheckIn.setLastModifiedBy(getLoginName());
				proCheckIn.setGmtModified(new Date());
				Resp resp = proCheckInService.update(proCheckIn);
				
				transResult.setCode(resp.getCode());
				transResult.setMsg(resp.getMsg());
			}
			
			return transResult;
		}

	  /**
	   * 查询列表
	   * @param pager
	   * @return
	   */
		@PostMapping("list")
		public TransResult list(@RequestParam(name = "page", defaultValue = "1") int page,
                            @RequestParam(name = "rows", defaultValue = "10") int rows,ProCheckIn proCheckIn) {
			Pager<ProCheckIn> result = proCheckInService.findListByCondition(page,rows,proCheckIn);
			return success(result);
		}
		
		/** 
		 * @Title proHandInCreate
		 * @Description 车辆灯登记新增
		 * @author luoteng
		 * @date 2018年7月10日:上午9:41:05
		 * @param list
		 * @return TransResult
		 */
		@PostMapping("/batch/insert")
		public TransResult proHandInCreate(@RequestBody List<ProCheckIn> list) {
			TransResult transResult = new TransResult();
			if(list == null || list.isEmpty()){
				transResult.setCode(Constant.FAIL);
				transResult.setMsg("请选择原材料型号及数量！");
				return transResult;
			}else{
				String checkInNo = wmsCommonService.getProShortSeq5(Constant.SEQ_PREFIX_SHORT_PRO_DJ, Constant.SEQ_PREFIX_SHORT_REDIS_PRO_DJ, 1).get(0);
				Resp resp = proCheckInService.batchInsert(list, checkInNo, getLoginName());
				
				transResult.setCode(resp.getCode());
				transResult.setMsg(resp.getMsg());
			}
			
			return transResult;
		}
		
		/** 
		* @Title: createBarcode 
		* @Description: 根据登记单号生成条码
		* @param @param rawCarCheckIn
		* @param @return  参数说明 
		* @return TransResult    返回类型
		* @author luoteng 
		* @date 2018年11月5日 上午11:37:45 
		* @throws 
		*/
		@PostMapping("barcode/create")
		public TransResult createBarcode(ProCheckIn proCheckIn) {
			TransResult transResult = new TransResult();
			if(proCheckIn.getCheckInNo() == null){
				transResult.setCode(Constant.FAIL);
				transResult.setMsg("请选择登记单号！");
				return transResult;
			}else{
				proCheckIn.setActiveFlag("1");
				
				String key = Constant.PRO_BARCODE_PREFIX + proCheckIn.getCheckInNo();
				if (stringRedisTemplate.hasKey(key)) {
					transResult.setCode(Constant.FAIL);
					transResult.setMsg("当前登记单号正在处理中，请勿重复提交！");
					return transResult;
				} else {
					stringRedisTemplate.opsForValue().set(key, "1", Constant.PRO_HAND_LOST_MINUTES, TimeUnit.MINUTES);//写入对象，并设置失效时间
					
					List<ProCheckIn> list = proCheckInService.queryByAny(proCheckIn);
					if(list == null){
						transResult.setCode(Constant.FAIL);
						transResult.setMsg("请选择登记单号！");
						return transResult;
					}else{
						ProCheckIn tmp = list.get(0);
//						是否生成条码： 1：是 0：否
						if(tmp.getUserDefined2() != null && tmp.getUserDefined2().equals("1")){
							transResult.setCode(Constant.FAIL);
							transResult.setMsg("该成品积压库存登记单号已经生成条码！");
							return transResult;
						}
					}
					
					HashMap<String, List<String>> barcodeMap = new HashMap<String, List<String>>();
					for(ProCheckIn tmp : list){
						List<String> barcodeList = wmsCommonService.getProBarCodeShortSeq5(tmp.getModelType() + "-J", tmp.getModelType(), tmp.getAmount());
//						barcodeMap.put(tmp.getModelType(), barcodeList);
						barcodeMap.put(tmp.getModel(), barcodeList);
					}
					
					try {
						Resp resp = proCheckInService.createBarcode(list, barcodeMap, getLoginName());

						transResult.setCode(resp.getCode());
						transResult.setMsg(resp.getMsg());
					}catch(RuntimeException e) {
						transResult.setCode(Constant.FAIL);
						transResult.setMsg(e.getMessage());
					}
					
					stringRedisTemplate.delete(key);//删除对象
				}
			}
			
			return transResult;
		}

	  /**
	   * 查询单条
	   * @param id
	   * @return
	   */
		@GetMapping("r/{id}")
		public TransResult queryById(@PathVariable String id) {
			ProCheckIn  proCheckIn = proCheckInService.findById(id);
			return success(proCheckIn);
		}

	  /**
	   * 修改记录
	   * @param proCheckIn
	   * @return
	   */
		@PostMapping("u")
		public TransResult update(ProCheckIn proCheckIn) {
			proCheckIn.preUpdate();
			Resp resp =  proCheckInService.update(proCheckIn);
	    	return fromResp(resp);
		}

}
